package com.sum.tea.xinlian

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.Spinner
import android.widget.TabHost
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import com.sum.common.base.BaseMvvmActivity
import com.sum.tea.R
import com.sum.tea.contants.AppConfig
import com.sum.tea.databinding.ActivityTab3TablelayoutBinding
import com.sum.tea.xinlian.viewmodel.Sub3TabViewModel
import com.uhf.api.cls.Reader

/**
 * RFID �����߲���ҳ�� ��������ǩ�ڴ棬д��ǩ�ڴ��������ǩ
 */
class Sub3TabActivity : BaseMvvmActivity<ActivityTab3TablelayoutBinding, Sub3TabViewModel>() {

    private lateinit var spinner_bankw: Spinner
    private lateinit var spinner_bankr: Spinner
    private lateinit var spinner_lockbank: Spinner
    private lateinit var spinner_locktype: Spinner
    private lateinit var editTextDatar: EditText
    private lateinit var editTextDataw: EditText
    private lateinit var editTextOpcountr: EditText
    private lateinit var editTextStartaddr: EditText
    private lateinit var editTextStartaddrw: EditText
    private lateinit var myapp: AppConfig

    override fun initView(savedInstanceState: Bundle?) {
        myapp = AppConfig.getInstance()
        setupTabHost()
        setupSpinners()
        setupRadioGroups()
        setupButtons()
        setupObservers()
        setupTabChangeListener()
    }

    private fun setupTabHost() {
        mBinding.tabhost3.setup()
        mBinding.tabhost3.tabWidget.orientation = LinearLayout.VERTICAL

        mBinding.tabhost3.addTab(
            mBinding.tabhost3.newTabSpec("tab1")
                .setIndicator(createIndicatorView(this, mBinding.tabhost3, AppConfig.Constr_sub3readmem))
                .setContent(R.id.tab3_sub_read)
        )
        mBinding.tabhost3.addTab(
            mBinding.tabhost3.newTabSpec("tab2")
                .setIndicator(createIndicatorView(this, mBinding.tabhost3, AppConfig.Constr_sub3writemem))
                .setContent(R.id.tab3_sub_write)
        )
        mBinding.tabhost3.addTab(
            mBinding.tabhost3.newTabSpec("tab3")
                .setIndicator(createIndicatorView(this, mBinding.tabhost3, AppConfig.Constr_sub3lockkill))
                .setContent(R.id.tab3_sub_lockkill)
        )

        // ���ó�ʼѡ��Tab�ı�����ɫ
        mBinding.tabhost3.tabWidget.getChildAt(0).setBackgroundColor(Color.BLUE)
    }

    private fun createIndicatorView(context: android.content.Context, tabHost: TabHost, title: String): View {
        val inflater = LayoutInflater.from(context)
        val tabIndicator = inflater.inflate(R.layout.tab_indicator_vertical, tabHost.tabWidget, false)
        val titleView: TextView = tabIndicator.findViewById(R.id.tv_indicator)
        titleView.text = title
        return tabIndicator
    }

    private fun setupSpinners() {
        val arradp_bank = ArrayAdapter<String>(
            this,
            android.R.layout.simple_spinner_item,
            AppConfig.spibank
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        val arradp_fbank = ArrayAdapter<String>(
            this,
            android.R.layout.simple_spinner_item,
            AppConfig.spifbank
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        val arradp_lockbank = ArrayAdapter<String>(
            this,
            android.R.layout.simple_spinner_item,
            AppConfig.spilockbank
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        val arradp_locktype = ArrayAdapter<String>(
            this,
            android.R.layout.simple_spinner_item,
            AppConfig.spilocktype
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        spinner_bankr = findViewById<View>(R.id.spinner_bankr) as Spinner
        spinner_bankw = findViewById<View>(R.id.spinner_bankw) as Spinner
        spinner_lockbank = findViewById<View>(R.id.spinner_lockbank) as Spinner
        spinner_locktype = findViewById<View>(R.id.spinner_locktype) as Spinner
        editTextDatar = findViewById<View>(R.id.editText_datar) as EditText
        editTextDataw = findViewById<View>(R.id.editText_dataw) as EditText
        editTextOpcountr = findViewById<View>(R.id.editText_opcountr) as EditText
        editTextStartaddr = findViewById<View>(R.id.editText_startaddr) as EditText
        editTextStartaddrw = findViewById<View>(R.id.editText_startaddrw) as EditText
        spinner_bankr.adapter = arradp_bank
        spinner_bankw.adapter = arradp_bank
        mBinding.spinnerOpfbank.adapter = arradp_fbank
        spinner_lockbank.adapter = arradp_lockbank
        spinner_locktype.adapter = arradp_locktype

        mBinding.spinnerOpfbank.setSelection(0)
        spinner_bankr.setSelection(1)
        spinner_bankw.setSelection(1)
        spinner_lockbank.setSelection(2)
        spinner_locktype.setSelection(1)
    }

    private fun setupRadioGroups() {
        // ����Ĭ��ѡ�е�RadioButton
        mBinding.radioGroupOpant.check(
            mBinding.radioGroupOpant.getChildAt(myapp.Rparams.opant - 1).id
        )
    }

    private fun setupButtons() {
        (findViewById<View>(R.id.button_read) as android.widget.Button).setOnClickListener {
            handleReadOperation()
        }

        (findViewById<View>(R.id.button_write) as android.widget.Button).setOnClickListener {
            handleWriteOperation()
        }

        (findViewById<View>(R.id.button_wepc) as android.widget.Button).setOnClickListener {
            handleWriteEpcOperation()
        }

        (findViewById<View>(R.id.button_lock) as android.widget.Button).setOnClickListener {
            handleLockOperation()
        }

        (findViewById<View>(R.id.button_kill) as android.widget.Button).setOnClickListener {
            handleKillOperation()
        }

        (findViewById<View>(R.id.button_testwrite) as android.widget.Button).setOnClickListener {
            handleTestWriteOperation()
        }

        (findViewById<View>(R.id.button_optimeset) as android.widget.Button).setOnClickListener {
            handleOptimeSet()
        }
    }

    private fun setupObservers() {
        mViewModel.toastMessage.observe(this) { message ->
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        }

        mViewModel.readData.observe(this) { data ->
            editTextDatar.setText(data)
            editTextDataw.setText(data)
        }
    }

    private fun setupTabChangeListener() {
        mBinding.tabhost3.setOnTabChangedListener { tabId ->
            val currentTab = mBinding.tabhost3.currentTab
            val tabIndicator = mBinding.tabhost3.tabWidget
            val selectedView = tabIndicator.getChildAt(currentTab)
            selectedView.setBackgroundColor(Color.BLUE)

            for (i in 0 until tabIndicator.childCount) {
                if (i != currentTab) {
                    tabIndicator.getChildAt(i).setBackgroundColor(Color.TRANSPARENT)
                }
            }
        }
    }

    override fun onBackPressed() {
        if ((System.currentTimeMillis() - myapp.exittime) > 2000) {
            Toast.makeText(this, AppConfig.Constr_Putandexit, Toast.LENGTH_SHORT).show()
            myapp.exittime = System.currentTimeMillis()
        } else {
            super.onBackPressed()
        }
    }

    // ���������
    private fun handleReadOperation() {
        try {
            val selectedOpant = getSelectedOpant()
            val isPasswordChecked = mBinding.checkBoxOpacepwd.isChecked
            val password = mBinding.editTextPassword.text.toString()

            mViewModel.SetOpant(selectedOpant)
            mViewModel.SetPassword(isPasswordChecked, password)

            val enableFilter = mBinding.radioGroupEnableopfil.checkedRadioButtonId == R.id.eoradio1
            val filterData = mBinding.editTextOpfilterdata.text.toString()
            val filterAddress = mBinding.editTextOpfilsadr.text.toString().toIntOrNull() ?: 0
            val filterBank = mBinding.spinnerOpfbank.selectedItemPosition
            val matchType = if (mBinding.radioGroupOpmatch.checkedRadioButtonId == R.id.omradio1) 1 else 0

            mViewModel.SetFiler(enableFilter, filterData, filterAddress, filterBank, matchType)

            val count = editTextDatar.text.toString().toIntOrNull() ?: 0
            val address = editTextStartaddr.text.toString().toIntOrNull() ?: 0
            val dataType = getSelectedDataType()
            val bank = spinner_bankr.selectedItemPosition
            val optime = myapp.Rparams.optime.toShort()

            mViewModel.readOperation(count, address, dataType, bank, password, optime)

        } catch (e: Exception) {
            Toast.makeText(this, "${AppConfig.Constr_excep} ${e.message}", Toast.LENGTH_SHORT).show()
            mViewModel.ClearFiler()
        }
    }

    // ����д����
    private fun handleWriteOperation() {
        try {
            val selectedOpant = getSelectedOpant()
            val isPasswordChecked = mBinding.checkBoxOpacepwd.isChecked
            val password = mBinding.editTextPassword.text.toString()

            mViewModel.SetOpant(selectedOpant)
            mViewModel.SetPassword(isPasswordChecked, password)

            val enableFilter = mBinding.radioGroupEnableopfil.checkedRadioButtonId == R.id.eoradio1
            val filterData = mBinding.editTextOpfilterdata.text.toString()
            val filterAddress = mBinding.editTextOpfilsadr.text.toString().toIntOrNull() ?: 0
            val filterBank = mBinding.spinnerOpfbank.selectedItemPosition
            val matchType = if (mBinding.radioGroupOpmatch.checkedRadioButtonId == R.id.omradio1) 1 else 0

            mViewModel.SetFiler(enableFilter, filterData, filterAddress, filterBank, matchType)

            val address = editTextStartaddrw.text.toString().toIntOrNull() ?: 0
            val dataType = getSelectedDataType()
            val bank = spinner_bankw.selectedItemPosition

            val data = when (dataType) {
                0 -> {
                    val hexStr = editTextDataw.text.toString()
                    ByteArray(hexStr.length / 2).apply {
                        myapp.Mreader.Str2Hex(hexStr, hexStr.length, this)
                    }
                }
                1 -> {
                    val ascStr = editTextDataw.text.toString()
                    if (ascStr.length % 2 != 0) "${ascStr}0" else ascStr
                    ascStr.toByteArray()
                }
                2 -> {
                    editTextDataw.text.toString().toByteArray(charset("GBK"))
                }
                else -> ByteArray(0)
            }

            val optime = myapp.Rparams.optime.toShort()

            mViewModel.writeOperation(data, address, bank, password, optime)

        } catch (e: Exception) {
            Toast.makeText(this, "${AppConfig.Constr_excep} ${e.message}", Toast.LENGTH_SHORT).show()
            mViewModel.ClearFiler()
        }
    }

    // ����дEPC����
    private fun handleWriteEpcOperation() {
        try {
            val selectedOpant = getSelectedOpant()
            val isPasswordChecked = mBinding.checkBoxOpacepwd.isChecked
            val password = mBinding.editTextPassword.text.toString()

            mViewModel.SetOpant(selectedOpant)
            mViewModel.SetPassword(isPasswordChecked, password)

            val enableFilter = mBinding.radioGroupEnableopfil.checkedRadioButtonId == R.id.eoradio1
            val filterData = mBinding.editTextOpfilterdata.text.toString()
            val filterAddress = mBinding.editTextOpfilsadr.text.toString().toIntOrNull() ?: 0
            val filterBank = mBinding.spinnerOpfbank.selectedItemPosition
            val matchType = if (mBinding.radioGroupOpmatch.checkedRadioButtonId == R.id.omradio1) 1 else 0

            mViewModel.SetFiler(enableFilter, filterData, filterAddress, filterBank, matchType)

            val dataType = getSelectedDataType()
            val data = when (dataType) {
                0 -> {
                    val hexStr = editTextDataw.text.toString()
                    ByteArray(hexStr.length / 2).apply {
                        myapp.Mreader.Str2Hex(hexStr, hexStr.length, this)
                    }
                }
                1 -> {
                    val ascStr = editTextDataw.text.toString()
                    if (ascStr.length % 2 != 0) "${ascStr}0" else ascStr
                    ascStr.toByteArray()
                }
                2 -> {
                    editTextDataw.text.toString().toByteArray(charset("GBK"))
                }
                else -> ByteArray(0)
            }

            val optime = myapp.Rparams.optime.toShort()

            mViewModel.writeEpcOperation(data, password, optime)

        } catch (e: Exception) {
            Toast.makeText(this, "${AppConfig.Constr_excep} ${e.message}", Toast.LENGTH_SHORT).show()
            mViewModel.ClearFiler()
        }
    }

    // ������������
    private fun handleLockOperation() {
        try {
            val selectedOpant = getSelectedOpant()
            val isPasswordChecked = mBinding.checkBoxOpacepwd.isChecked
            val password = mBinding.editTextPassword.text.toString()

            mViewModel.SetOpant(selectedOpant)
            mViewModel.SetPassword(isPasswordChecked, password)

            val enableFilter = mBinding.radioGroupEnableopfil.checkedRadioButtonId == R.id.eoradio1
            val filterData = mBinding.editTextOpfilterdata.text.toString()
            val filterAddress = mBinding.editTextOpfilsadr.text.toString().toIntOrNull() ?: 0
            val filterBank = mBinding.spinnerOpfbank.selectedItemPosition
            val matchType = if (mBinding.radioGroupOpmatch.checkedRadioButtonId == R.id.omradio1) 1 else 0

            mViewModel.SetFiler(enableFilter, filterData, filterAddress, filterBank, matchType)

            val lockBank = spinner_lockbank.selectedItemPosition
            val lockType = spinner_locktype.selectedItemPosition
            val lockObj = when (lockBank) {
                0 -> Reader.Lock_Obj.LOCK_OBJECT_ACCESS_PASSWD
                1 -> Reader.Lock_Obj.LOCK_OBJECT_KILL_PASSWORD
                2 -> Reader.Lock_Obj.LOCK_OBJECT_BANK1
                3 -> Reader.Lock_Obj.LOCK_OBJECT_BANK2
                4 -> Reader.Lock_Obj.LOCK_OBJECT_BANK3
                else -> Reader.Lock_Obj.LOCK_OBJECT_ACCESS_PASSWD
            }
            val lockTyp = when (lockType) {
                0 -> {
                    when (lockBank) {
                        0 -> Reader.Lock_Type.ACCESS_PASSWD_UNLOCK
                        1 -> Reader.Lock_Type.KILL_PASSWORD_UNLOCK
                        2 -> Reader.Lock_Type.BANK1_UNLOCK
                        3 -> Reader.Lock_Type.BANK2_UNLOCK
                        4 -> Reader.Lock_Type.BANK3_UNLOCK
                        else -> Reader.Lock_Type.ACCESS_PASSWD_UNLOCK
                    }
                }
                1 -> {
                    when (lockBank) {
                        0 -> Reader.Lock_Type.ACCESS_PASSWD_LOCK
                        1 -> Reader.Lock_Type.KILL_PASSWORD_LOCK
                        2 -> Reader.Lock_Type.BANK1_LOCK
                        3 -> Reader.Lock_Type.BANK2_LOCK
                        4 -> Reader.Lock_Type.BANK3_LOCK
                        else -> Reader.Lock_Type.ACCESS_PASSWD_LOCK
                    }
                }
                2 -> {
                    when (lockBank) {
                        0 -> Reader.Lock_Type.ACCESS_PASSWD_PERM_LOCK
                        1 -> Reader.Lock_Type.KILL_PASSWORD_PERM_LOCK
                        2 -> Reader.Lock_Type.BANK1_PERM_LOCK
                        3 -> Reader.Lock_Type.BANK2_PERM_LOCK
                        4 -> Reader.Lock_Type.BANK3_PERM_LOCK
                        else -> Reader.Lock_Type.ACCESS_PASSWD_PERM_LOCK
                    }
                }
                else -> Reader.Lock_Type.ACCESS_PASSWD_UNLOCK
            }

            val optime = myapp.Rparams.optime.toShort()

            mViewModel.lockOperation(lockObj, lockTyp, password, optime)

        } catch (e: Exception) {
            Toast.makeText(this, "${AppConfig.Constr_excep} ${e.message}", Toast.LENGTH_SHORT).show()
            mViewModel.ClearFiler()
        }
    }

    // �������ٱ�ǩ����
    private fun handleKillOperation() {
        try {
            val selectedOpant = getSelectedOpant()
            val password = mBinding.editTextPassword.text.toString()

            mViewModel.SetOpant(selectedOpant)
            mViewModel.SetPassword(mBinding.checkBoxOpacepwd.isChecked, password)

            val enableFilter = mBinding.radioGroupEnableopfil.checkedRadioButtonId == R.id.eoradio1
            val filterData = mBinding.editTextOpfilterdata.text.toString()
            val filterAddress = mBinding.editTextOpfilsadr.text.toString().toIntOrNull() ?: 0
            val filterBank = mBinding.spinnerOpfbank.selectedItemPosition
            val matchType = if (mBinding.radioGroupOpmatch.checkedRadioButtonId == R.id.omradio1) 1 else 0

            mViewModel.SetFiler(enableFilter, filterData, filterAddress, filterBank, matchType)

            val optime = myapp.Rparams.optime.toShort()

            mViewModel.killOperation(password, optime)

        } catch (e: Exception) {
            Toast.makeText(this, "${AppConfig.Constr_excep} ${e.message}", Toast.LENGTH_SHORT).show()
            mViewModel.ClearFiler()
        }
    }

    // �������д����
    private fun handleTestWriteOperation() {
        try {
            val selectedOpant = getSelectedOpant()
            val isPasswordChecked = mBinding.checkBoxOpacepwd.isChecked
            val password = mBinding.editTextPassword.text.toString()

            mViewModel.SetOpant(selectedOpant)
            mViewModel.SetPassword(isPasswordChecked, password)

            val enableFilter = mBinding.radioGroupEnableopfil.checkedRadioButtonId == R.id.eoradio1
            val filterData = mBinding.editTextOpfilterdata.text.toString()
            val filterAddress = mBinding.editTextOpfilsadr.text.toString().toIntOrNull() ?: 0
            val filterBank = mBinding.spinnerOpfbank.selectedItemPosition
            val matchType = if (mBinding.radioGroupOpmatch.checkedRadioButtonId == R.id.omradio1) 1 else 0

            mViewModel.SetFiler(enableFilter, filterData, filterAddress, filterBank, matchType)

            val address = editTextStartaddrw.text.toString().toIntOrNull() ?: 0
            val bank = spinner_bankw.selectedItemPosition
            val dataType = getSelectedDataType()
            val optime = myapp.Rparams.optime.toShort()

            mViewModel.testWriteOperation(address, bank, dataType, password, optime)

        } catch (e: Exception) {
            Toast.makeText(this, "${AppConfig.Constr_excep} ${e.message}", Toast.LENGTH_SHORT).show()
            mViewModel.ClearFiler()
        }
    }

    // �������ò���ʱ��
    private fun handleOptimeSet() {
        val optimeStr = mBinding.editTextOptime.text.toString()
        val optime = optimeStr.toIntOrNull()
        if (optime != null) {
            mViewModel.setOptime(optime)
            Toast.makeText(this, AppConfig.Constr_ok, Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "${AppConfig.Constr_excep} Invalid Optime", Toast.LENGTH_SHORT).show()
        }
    }

    // ��ȡѡ�е�����
    private fun getSelectedOpant(): Int {
        val selectedId = mBinding.radioGroupOpant.checkedRadioButtonId
        val radioButton: RadioButton = mBinding.radioGroupOpant.findViewById(selectedId)
        return mBinding.radioGroupOpant.indexOfChild(radioButton)
    }

    // ��ȡѡ�е���������
    private fun getSelectedDataType(): Int {
        return when (mBinding.radioGroupDatatype.checkedRadioButtonId) {
            R.id.RadioButton_hex -> 0
            R.id.RadioButton01 -> 1
            R.id.RadioButton03 -> 2
            else -> 0
        }
    }

}
